package com.gscitysfy.cus.drain.modules.duty.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gscitysfy.cloudfrmwk.portal.feign.DictionaryService;
import com.gscitysfy.cloudfrmwk.security.definition.core.HerodotusUserDetails;
import com.gscitysfy.cloudfrmwk.security.utils.SecurityUtils;

import com.gscitysfy.cus.drain.constants.DicConstant;
import com.gscitysfy.cus.drain.modules.duty.entity.MoperDutyMnClasses;
import com.gscitysfy.cus.drain.modules.duty.entity.MoperDutyMnPeople;
import com.gscitysfy.cus.drain.modules.duty.entity.MoperDutyRlLog;
import com.gscitysfy.cus.drain.modules.duty.mapper.MoperDutyRlLogMapper;
import com.gscitysfy.cus.drain.modules.duty.service.IMoperDutyRlLogService;
import com.gscitysfy.cus.drain.modules.duty.vo.MoperDutyRlLogVo;
import com.gscitysfy.cus.drain.utils.PdfUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author admin
 * @since 2022-03-28 15:38:59
 */
@Service
@Slf4j
public class MoperDutyRlLogServiceImpl extends ServiceImpl<MoperDutyRlLogMapper, MoperDutyRlLog> implements IMoperDutyRlLogService {


    @Autowired
    MoperDutyRlLogMapper moperDutyRlLogMapper;

    @Resource
    private DictionaryService dictionaryService;


    static final String DATATYPE1 = "dutyType1";
    static final String DETERIORATES3 = "dutyRecordStatus3";
    static final String DECORATES1 = "dutyRecordStatus1";

    @Override
    public int addMoperDutyRlLog(MoperDutyRlLog moperDutyRlLog) {
        return moperDutyRlLogMapper.insert(moperDutyRlLog);
    }

    @Override
    public int updateMoperDutyRlLog(MoperDutyRlLog moperDutyRlLog) {
        return moperDutyRlLogMapper.updateById(moperDutyRlLog);
    }

    @Override
    public Boolean deleteMoperDutyRlLog(String ids) {
        String[] split = ids.split(",");
        for (int i = 0; i < split.length; i++) {
            MoperDutyRlLog moperDutyRlLog = moperDutyRlLogMapper.selectById(split[i]);
            if (DETERIORATES3.equals(moperDutyRlLog.getCoamClassessStatus())) {
                return false;
            }
        }
        return this.removeByIds(Arrays.asList(split));
    }

    @Override
    public MoperDutyRlLog detailMoperDutyRlLog(String id) {
        MoperDutyRlLog moperDutyRlLog = moperDutyRlLogMapper.selectById(id);
        moperDutyRlLog.setClassessName(moperDutyRlLogMapper.getBcmc(moperDutyRlLog.getCoamClassessId()));
        //人员相关未完成
        moperDutyRlLog.setPeopletype(moperDutyRlLogMapper.getPeople(moperDutyRlLog.getCoamDutyPersonId()).getCoamPersonType());
        moperDutyRlLog.setPersonUsername(moperDutyRlLogMapper.getPeople(moperDutyRlLog.getCoamDutyPersonId()).getCoamPersonUsername());
        return moperDutyRlLog;
    }

    @Override
    public IPage<MoperDutyRlLog> getAll(Page<MoperDutyRlLog> page, String startTime, String endTime, String rylx, String bc, String zbry) {
        HerodotusUserDetails principal = SecurityUtils.getPrincipal();
        if (principal == null) {
            return null;
        }
        MoperDutyMnPeople people = moperDutyRlLogMapper.getPeople(principal.getUserId());
        List<String> listPerson = new ArrayList<>();
        //值班员只能查看自己的日志
        if (ObjectUtil.isNotEmpty(people)){
            if (DATATYPE1.equals(people.getCoamPersonType())) {
                listPerson.add(people.getCoamPersonId());
            } else {
                //值班长可查看与值班长同一班次下所有值班人员日志
                listPerson = moperDutyRlLogMapper.getPersonByDuty(people.getCoamPersonId());
            }
        }
        return moperDutyRlLogMapper.getAll(page, startTime, endTime, rylx, bc, zbry, listPerson);
    }

    @Override
    public List<MoperDutyMnPeople> allPeople() {
        return moperDutyRlLogMapper.allPeople();
    }

    @Override
    public List<MoperDutyMnClasses> allClassess(String coamClassessType, String coamClassessCode, Long coamClassessStatu) {
        return moperDutyRlLogMapper.allClassess(coamClassessType, coamClassessCode,  coamClassessStatu);
    }

    @Override
    public int audit(String ids,String coamLogRemark,String coamClassessStatus) {
        String[] split = ids.split(",");
        for (int i = 0; i < split.length; i++) {
            MoperDutyRlLog moperDutyRlLog = moperDutyRlLogMapper.selectById(split[i]);
            moperDutyRlLog.setCoamApproveOpinion(coamLogRemark);
            moperDutyRlLog.setCoamClassessStatus(coamClassessStatus);
            moperDutyRlLogMapper.updateById(moperDutyRlLog);
        }
        return 1;
    }

    @Override
    public MoperDutyRlLog record(String id) {
        return moperDutyRlLogMapper.selectById(id);
    }

    /**
     * 下载值班日志PDF（多个PDF压缩）
     * @param listId 主键集合
     * @param response 响应
     */
    @Override
    public void recordDownload(List<String> listId, HttpServletResponse response){
        String templateName = "/template/dutyLogTemplate.pdf";
        String fileName = "值班日志导出";
        List<MoperDutyRlLogVo> listLog = moperDutyRlLogMapper.listByIds(listId);
        //翻译运行状态编码
        Map<String, String> runStatusMap = dictionaryService.getDictionaryMap(DicConstant.LOG_RUN_STATUS).getData();
        listLog = listLog.stream().peek(
                item -> item.setCoamRunStatus(runStatusMap.get(item.getCoamRunStatus()))
        ).collect(Collectors.toList());
        List<Map<String, Object>> listData = new ArrayList<>();
        if (!listLog.isEmpty()){
            for (MoperDutyRlLogVo moperDutyRlLog:listLog){
                // 装配数据
                Map<String, Object> data = new HashMap<>(16);
                data.put("coamClassessStarttime", moperDutyRlLog.getCoamClassessStarttime());
                data.put("coamClassessEndtime",moperDutyRlLog.getCoamClassessEndtime());
                data.put("coamRunStatus",moperDutyRlLog.getCoamRunStatus());
                data.put("coamLogRemark",moperDutyRlLog.getCoamLogRemark());
                data.put("coamDutyDate",moperDutyRlLog.getCoamDate());
                data.put("coamPesonName",moperDutyRlLog.getCoamPesonName());
                data.put("coamClassName",moperDutyRlLog.getCoamClassName());
                //多个文件打包压缩时，单独设置文件名称
                data.put("fileName",fileName + "-" + moperDutyRlLog.getCoamKid());
                listData.add(data);
            }
            //单条数据生成单个PDF，多条则自动打包成ZIP
            if (listData.size() == 1){
                Map<String, Object> data = listData.get(0);
                PdfUtil.generatePDFDoc(fileName,response,data);
            }else{
                PdfUtil.generatePDFZip(fileName,response,listData);
            }
        }

    }

    @Override
    public MoperDutyMnPeople people() {
        HerodotusUserDetails principal = SecurityUtils.getPrincipal();
        if (principal == null) {
            return null;
        }
        return moperDutyRlLogMapper.getPeople(principal.getUserId());
    }

}
